<template>
  <el-card class="update-password">
    <el-form class="login-box1" ref="updatePasswordForm" :model="updatePasswordForm" :rules="rules" label-width="100px">
      <h3 class="login-title">修改密码</h3>
      <el-form-item label="原密码" prop="oldpassword">
        <el-input type="password" show-password auto-complete="off" placeholder="请输入原密码" v-model="updatePasswordForm.oldpassword"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input type="password" show-password auto-complete="off" placeholder="请设置新密码" v-model="updatePasswordForm.password"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="password2">
        <el-input type="password" show-password auto-complete="off" placeholder="请确认新密码" v-model="updatePasswordForm.password2"></el-input>
      </el-form-item>
      <el-form-item style="float:right">
        <el-button type="primary" @click="updatePassword">修改密码</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import md5 from 'js-md5'
import Vue from 'vue'
import { updateUserPassword } from '@/request/user/user-api'
Vue.prototype.$md5 = md5
export default {
  name: "reset",
  data() {
    const validateNewPassword = (rule, value, callback) => {
      let regex=/^(?=.*\d)(?=.*[a-zA-Z])(?=.*[^\da-zA-Z\s]).{8,20}$/
      if (value === this.updatePasswordForm.oldpassword) {
        callback(new Error("新密码不能与原密码相同!"));
      } else if(!regex.test(value)) {
        callback(new Error("密码必须包含字母、数字、特殊字符且长度为8-20位"));
      }else {
        callback();
      }
    };
    const validateNewPassword2 = (rule, value, callback) => {
      let regex=/^(?=.*\d)(?=.*[a-zA-Z])(?=.*[^\da-zA-Z\s]).{8,20}$/
      if (value !== this.updatePasswordForm.password) {
        callback(new Error("与新密码不一致!"));
      } else if(!regex.test(value)) {
        callback(new Error("密码必须包含字母、数字、特殊字符且长度为8-20位"));
      } else {
        callback();
      }
    };
    return {
      updatePasswordForm: {
        oldpassword: "",
        password: "",
        password2: "",
      },

      // 表单校验
      rules: {
        oldpassword: [
          { required: true, message: "请输入原密码", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请设置新密码", trigger: "blur" },
          { validator: validateNewPassword, trigger: "blur" },
        ],
        password2: [
          { required: true, message: "请确认新密码", trigger: "blur" },
          { validator: validateNewPassword2, trigger: "blur" },
        ],
      },
    };
  },
 methods:{
   updatePassword(){
     this.$refs.updatePasswordForm.validate(valid => {
       if (!valid) {
         this.$message.error('存在错误内容，请完善信息！')
         return false
       } else {
         this.$confirm('确定修改登录密码吗？', '提示',
             {
               'confirmButtonText': '确定',
               'cancelButtonText': '取消',
               'type': 'warning'
             }).then(async () => {
           const data = {
             oldPassword: this.$md5(this.updatePasswordForm.oldpassword),
             newPassword: this.$md5(this.updatePasswordForm.password)
           }
           let res = await updateUserPassword(data)
           if (res && res.code === 200) {
             this.$message.success("修改密码成功，请重新登录")
             //清除localStorage
             localStorage.removeItem('accessToken')
             localStorage.removeItem('refreshToken')
             localStorage.removeItem('expert-userInfo')
             //跳转登录界面
             await this.$router.push('/login')
           }else {
             this.$message.error(res.msg?res.msg:"修改密码失败")
           }
         }).catch((e)=>{
            this.$message.error(e)
         })
       }
     })
   },
   reset(){
     this.$nextTick(()=>{
       this.$refs['updatePasswordForm'].resetFields();//清空表单
     });
   }
 }
};
</script>
<style scoped lang="less">
.update-password{
  width: 500px;
  margin: 200px auto;
  padding:0 20px;
  border-radius: 10px;
}
.login-title{
  text-align: center;
}
</style>
